#include "menuFiles.h"


TTF_Font * entry_font;
SDL_Surface * background;
SDL_Surface * folder_icon;
SDL_Surface * file_icon;

int getDirContent(FilesMenuState *state, mpd_Connection *conn, char *path)
{


    mpd_InfoEntity * entity;
    //printf("Path: %s\n", path);
    strcpy(state->currentPath, path);

    int count = 0;
    mpd_sendLsInfoCommand(conn, path);

    state->lines = 0;
    state->selectedLine = 0;

    if (conn->error)
    {
        char errortxt[50];
        sprintf(errortxt,"Error: %s - %d\n", conn->errorStr, conn->errorCode);
        app_error(errortxt);
        return 1;
    }

    //FileMenuEntry ** entryArray = state->entries;

    while ((entity = mpd_getNextInfoEntity(conn)) && count
            < MAX_FILES_DIRECTORIES)
    {

        if (entity->type == MPD_INFO_ENTITY_TYPE_DIRECTORY)
        {
            //char *desc;

            FileMenuEntry * entry = &state->entries[count];
            entry->isDirectory = 1;

            getDescriptionFromPath(entity->info.directory->path,entry->description);
            //strcpy(entry->description, desc);
            //free(desc);

            strcpy(entry->path, entity->info.directory->path);

            count++;
        }
        else if (entity->type == MPD_INFO_ENTITY_TYPE_SONG)
        {

            FileMenuEntry * entry = &state->entries[count];
            entry->isDirectory = 0;

            mpd_Song * song = entity->info.song;

            //Vamos a generar la descripcion
            if (song->artist != NULL && song->title != NULL)
            {
                strcpy(entry->description, song->artist);
                strcat(entry->description, " - ");
                strcat(entry->description, song->title);
            }
            else
            {
                //printf("Aqui si deberia");
                getDescriptionFromPath(song->file, entry->description);
            }

            strcpy(entry->path, song->file);
            count++;

        }

        mpd_freeInfoEntity(entity);
    }

    state->lines = count;
    state->selectedLine = 0;

    mpd_finishCommand(conn);

    return 1;
}

menu * createFilesMenu()
{
    menu *FilesMenu = (menu *) malloc(sizeof(menu));

    //Set up handlers
    FilesMenu->handleC = handleCFilesMenu;
    FilesMenu->handleDown = handleDownFilesMenu;
    FilesMenu->handleLT = handleLTFilesMenu;
    FilesMenu->handleRT = handleRTFilesMenu;
    FilesMenu->handleS = handleSFilesMenu;
    FilesMenu->handleT = handleTFilesMenu;
    FilesMenu->handleUp = handleUpFilesMenu;
    FilesMenu->handleX = handleXFilesMenu;

    //Set up config calls
    FilesMenu->aboutToHide = aboutToHideFilesMenu;
    FilesMenu->aboutToShow = aboutToShowFilesMenu;
    FilesMenu->init = initFilesMenu;
    FilesMenu->destroy = destroyFilesMenu;

    //State
    FilesMenuState *state = malloc(sizeof(FilesMenuState));

    state->lines = 0;
    state->selectedLine = 0;
    state->previousSelectedLineHistoryIndex = 0;
    strcpy(state->currentPath, "/");

    FilesMenu->state = state;

    entry_font = sdl_load_font("FreeMonoBold.ttf",12);
    background = sdl_load_image("fondofiles.png");
    folder_icon = sdl_load_image("folder.png");
    file_icon = sdl_load_image("music.png");


    return FilesMenu;
}

int handleXFilesMenu(void *vstate, mpd_Connection* connection)
{

    FilesMenuState *state = (FilesMenuState *) vstate;
    if (state->lines > 0)
    {

        FileMenuEntry entry = state->entries[state->selectedLine];
        if (entry.isDirectory)
        {

            state->previouslySelectedLine[state->previousSelectedLineHistoryIndex]
            = state->selectedLine;
            state->previousSelectedLineHistoryIndex++;
            getDirContent(state, connection, entry.path);

            if (state->lines > 0)
            {

                paintFilesMenu(state, connection);
            }
        }

    }
    return 1;
}

int handleTFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState *state = (FilesMenuState *) vstate;

    //int retries = 0;
    if (strcmp(state->currentPath, "/") != 0)
    {
        char previousDirectory[100];
        getPreviousDirectory(state->currentPath,previousDirectory);
        getDirContent(state, connection, previousDirectory);

        if (state->lines > 0)
        {
            state->selectedLine
            = state->previouslySelectedLine[state->previousSelectedLineHistoryIndex
                                            - 1];
            state->previousSelectedLineHistoryIndex--;
            paintFilesMenu(state, connection);
        }


    }

    return 1;
}

int handleSFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState * state = (FilesMenuState *) vstate;
    if (state->lines > 0)
    {
        //printf("Path %s", state->entries[state->selectedLine].path);
        mpd_sendAddCommand(connection, state->entries[state->selectedLine].path);
        mpd_finishCommand(connection);
    }

    return 1;
}

int handleCFilesMenu(void *vstate, mpd_Connection* connection)
{

    FilesMenuState * state = (FilesMenuState *) vstate;
    if (state->lines > 0)
    {
        int playing = 0;
        //printf("Status!");
        mpd_sendStatusCommand(connection);
        mpd_Status * status = mpd_getStatus(connection);
        if (status)
        {
            playing = status->state == MPD_STATUS_STATE_PAUSE || status->state
                      == MPD_STATUS_STATE_PLAY;
            //printf("Playing %d", playing);
            mpd_freeStatus(status);
            mpd_finishCommand(connection);

            mpd_sendClearCommand(connection);
            mpd_finishCommand(connection);
            mpd_sendAddCommand(connection,
                               state->entries[state->selectedLine].path);
            mpd_finishCommand(connection);

            if (playing)
            {
                mpd_sendPlayCommand(connection, 0);
                mpd_finishCommand(connection);
            }
        }
        else
        {
            app_error("Status NULLL!!!!");
        }

    }

    return 1;
}

int handleUpFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState * menuState = (FilesMenuState *) vstate;
    menuState->selectedLine--;
    if (menuState->selectedLine < 0)
        menuState->selectedLine = 0;
    else
        paintFilesMenu(menuState, connection);
    return 1;
}

int handleDownFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState * menuState = (FilesMenuState *) vstate;
    if (menuState->selectedLine != (menuState->lines - 1))
    {
        menuState->selectedLine++;
        paintFilesMenu(menuState, connection);
    }

    return 1;
}

int handleRTFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState * menuState = (FilesMenuState *) vstate;
    menuState->selectedLine += 10;
    if (menuState->selectedLine >= menuState->lines)
    {
        menuState->selectedLine = menuState->lines - 1;
    }

    return paintFilesMenu(menuState, connection);
}

int handleLTFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState * menuState = (FilesMenuState *) vstate;
    menuState->selectedLine -= 10;
    if (menuState->selectedLine < 0)
    {
        menuState->selectedLine = 0;
    }

    return paintFilesMenu(menuState, connection);

}

int initFilesMenu(void *vstate, mpd_Connection* connection)
{
    FilesMenuState *state = (FilesMenuState *) (vstate);

    getDirContent(state, connection, "/");
    //return paintFilesMenu(state, connection);
    return 1;

}

int paintFilesMenu(void *vstate, mpd_Connection* connection)
{
    int inicio = 0;
    int cuantos = 0;
    int idx = 0;

    FilesMenuState * menuState = (FilesMenuState *) vstate;

    //Pintar fondo
    sdl_clear_screen(0,0,0);
    SDL_Rect position = {0,0};
    sdl_paint_surface(background,&position);

    SDL_Surface * txt = sdl_draw_text(entry_font,255,255,255,0,0,0,0,0,"Music broser",blended);
    //SDL_Surface * txt = sdl_draw_text(entry_font,255,255,255,0,0,0,0,0,debugtxt,blended);
    position.x = 5;
    position.y = 0;
    sdl_paint_surface(txt,&position);

    inicio = menuState->selectedLine - (MAX_LINES - 1 );
    if (inicio < 0)
        inicio = 0;

    cuantos = inicio + ((menuState->lines < MAX_LINES) ? menuState->lines : MAX_LINES);



    for (; inicio < cuantos; inicio++,idx++)
    {
        SDL_Surface * text;
        SDL_Surface * icon;

        FileMenuEntry entry = menuState->entries[inicio];

        if(entry.isDirectory)
        {
            icon = folder_icon;
        }
        else
        {
            icon = file_icon;
        }



        if(inicio == menuState->selectedLine)
        {
            text = sdl_draw_text(entry_font,255,100,100,0,0,0,0,0,entry.description,blended);
        }
        else
        {
            text = sdl_draw_text(entry_font,255,255,255,0,0,0,0,0,entry.description,blended);
        }

        SDL_Rect iconRect;
        iconRect.y = 15 * (idx+1);
        iconRect.x = 5;

        sdl_paint_surface(icon,&iconRect);

        SDL_Rect textRect;

        textRect.x = 26;
        textRect.y = 15 * (idx+1);
        textRect.w = 272-26;
        textRect.h = text->h;

        sdl_paint_surface(text,&textRect);
        SDL_FreeSurface(text);



        /*printf("%s\n", entry.description);
        if (inicio == menuState->selectedLine)
        {
            pspDebugScreenSetTextColor(0xFFFFFF);
        }*/

    }

    sdl_flip();

    return 1;
}

int aboutToShowFilesMenu(void *vstate, mpd_Connection* connection)
{
    paintFilesMenu(vstate, connection);
    return 1;
}

int aboutToHideFilesMenu(void *vstate, mpd_Connection* connection)
{
    return 1;
}

int destroyFilesMenu(void* vstate, mpd_Connection* connection)
{
    return 1;
}
